import { createWebHashHistory, createRouter, RouteRecordRaw } from "vue-router";
import { ref } from "vue";
import { PracticeItem, generateMenu } from "@/components/GenerateMenu";
import addDynamicRoute from "@/components/GenerateRoutes";
import NProgress from "nprogress";
import "nprogress/nprogress.css";

import Home from "../views/Home.vue";
import NotFound from "@/views/error/404.vue";

const routes = [
  { path: "/", name: "Home", component: Home, meta: { title: "Home" } },
  {
    path: "/404",
    name: "ErrorPage",
    component: NotFound,
    meta: { title: "404 Error" }
  },
  {
    path: "/:catchAll(.*)", // 捕获所有未定义的路由
    redirect: { name: "ErrorPage" }
  }
];

const practices = ref<PracticeItem>({
  name: "/",
  path: "/",
  title: "root",
  children: []
});

const router = createRouter({
  history: createWebHashHistory(),
  routes
});

const reGenMenus = async () => {
  practices.value = generateMenu();
  const routes: Array<RouteRecordRaw> = addDynamicRoute(practices.value);
  routes.forEach(async route => {
    await router.addRoute(route);
  });
};

reGenMenus();

// 在路由导航开始时启动进度条
router.beforeEach(async () => {
  NProgress.start(); // 开始进度条
  // next();
});

// 在路由导航结束时完成进度条
router.afterEach(() => {
  NProgress.done(); // 完成进度条
});

export default router;
